/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.lswms.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import com.lswms.annotation.Login;
import com.lswms.annotation.LoginUser;
import com.lswms.common.redis.RedisUtils;
import com.lswms.common.utils.MoneyUtil;
import com.lswms.common.utils.Result;
import com.lswms.common.utils.ZqDateUtil;
import com.lswms.common.validator.ValidatorUtils;
import com.lswms.dto.YnUserDTO;
import com.lswms.dto.vo.req.LoginReq;
import com.lswms.dto.vo.req.UpdateDataReq;
import com.lswms.dto.vo.req.UpdateUserInfoReq;
import com.lswms.dto.vo.resp.LoginResp;
import com.lswms.dto.vo.resp.OrderCityDataResp;
import com.lswms.dto.vo.resp.OrderDataListResp;
import com.lswms.dto.vo.resp.OrderListResp;
import com.lswms.dto.vo.resp.SevenOrderDataResp;
import com.lswms.dto.vo.resp.TodayDataResp;
import com.lswms.entity.YnUserEntity;
import com.lswms.redis.SysParamsRedis;
import com.lswms.service.YnUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import springfox.documentation.annotations.ApiIgnore;

import com.alibaba.fastjson.JSON;

/**
 * 大数据接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/api/bigData")
@Api(tags="大数据接口")
@Slf4j
public class BigDataController {
	
    @Autowired
    private SysParamsRedis sysParamsRedis;
    
    @Autowired
    private RedisUtils redisUtils;
    
    
    /**
     * 今日数据
     * @param dto
     * @param request
     * @return
     */
    @PostMapping("todayData")
    @ApiOperation("今日数据")
    public Result<TodayDataResp> todayData(HttpServletRequest request){
    	TodayDataResp resp = new TodayDataResp();
    	String ym = ZqDateUtil.yyyy_MM();
    	String ymd = ZqDateUtil.yyyyMMdd(ZqDateUtil.getNow());
    	String randomCount = sysParamsRedis.get("random"+ym);
    	//随机添加数量
    	int count = 0;
    	if(StringUtils.isBlank(randomCount)){
    		count = getRandom(1,20);
    		randomCount = "0";
    	}else{
    		if(Integer.parseInt(randomCount) >= 500){
    			count = 0;
    		}else{
    			count = getRandom(1,20);
    		}
    	}
    	Object ymdCount = redisUtils.hGet("nowCount:"+ymd, ymd);
    	if(ymdCount != null){
    		count = 0;
    	}
    	
    	String nowCount = sysParamsRedis.get("nowCount");
    	if(StringUtils.isBlank(nowCount)){
    		nowCount = "3500";
    	}
    	int totalCount = Integer.parseInt(nowCount) + count;
    	sysParamsRedis.set("nowCount", totalCount+"");
    	redisUtils.hSet("nowCount:"+ymd, ymd, totalCount+"");
    	sysParamsRedis.set("random"+ym,(Integer.parseInt(randomCount) + count)+"");
    	
    	//当前充值   订单总数
    	String charge = (String)redisUtils.hGet("Charge:"+ymd, ymd);
    	String order = (String)redisUtils.hGet("Order:"+ymd, ymd);
    	BigDecimal todayCharge = BigDecimal.ZERO;
    	BigDecimal todayTotalOrder = BigDecimal.ZERO;
    	
    	if(StringUtils.isBlank(charge)){
    		//今日充值金额
        	todayCharge = new BigDecimal(totalCount).multiply(getRandomRate(80,90))
        			.multiply(getRandomRate(70,80)).multiply(new BigDecimal(getRandom(8,15)))
        			.multiply(new BigDecimal(getRandom(2,20)));
        	redisUtils.hSet("Charge:"+ymd, ymd, MoneyUtil.bigDecimal2String(todayCharge, 0));
    	}else{
    		todayCharge = new BigDecimal(charge);
    	}
    	if(StringUtils.isBlank(order)){
    		//今日订单数
        	todayTotalOrder = todayCharge.multiply(new BigDecimal(getRandom(1,2)));
        	redisUtils.hSet("Order:"+ymd, ymd, MoneyUtil.bigDecimal2String(todayTotalOrder, 0));
    	}else{
    		todayTotalOrder = new BigDecimal(order);
    	}
    	//今日用户总数
    	BigDecimal a = new BigDecimal(totalCount).multiply(getRandomRate(70,80)).multiply(new BigDecimal(getRandom(8,15)));
    	String todayUserCount = MoneyUtil.bigDecimal2String(a,0);
    	String todayUserCounts = (String)redisUtils.hGet("todayUserCount:"+ymd, ymd);
    	if(StringUtils.isBlank(todayUserCounts)){
    		redisUtils.hSet("todayUserCount:"+ymd, ymd, todayUserCount);
    	}else{
    		todayUserCount = todayUserCounts;
    	}
    	String date = ZqDateUtil.yyyyMMdd(ZqDateUtil.addDate(ZqDateUtil.getNow(), -1, Calendar.DAY_OF_MONTH));
    	
    	String str1 = (String)redisUtils.hGet("todayUserCount:"+date, date);
    	String str2 = (String)redisUtils.hGet("newUser:"+date, date);
    	String str3 = (String)redisUtils.hGet("AvgUserPlam:"+date, date);
    	String str4 = (String)redisUtils.hGet("UserRate:"+date, date);
    	String str5 = (String)redisUtils.hGet("PlamRate:"+date, date);

    	String newUser = MoneyUtil.bigDecimal2String(new BigDecimal(todayUserCount).multiply(getRandomRate(6,8)), 0);
    	String newUsers = (String)redisUtils.hGet("newUser:"+ymd, ymd);
    	if(StringUtils.isBlank(newUsers)){
    		redisUtils.hSet("newUser:"+ymd, ymd, newUser);
    	}
    	String AvgUserPlam = (String)redisUtils.hGet("AvgUserPlam:"+ymd, ymd);
    	if(StringUtils.isBlank(AvgUserPlam)){
    		redisUtils.hSet("AvgUserPlam:"+ymd, ymd, getRandom(8,15)+"");
    	}
    	String UserRate = (String)redisUtils.hGet("UserRate:"+ymd, ymd);
    	if(StringUtils.isBlank(UserRate)){
    		redisUtils.hSet("UserRate:"+ymd,ymd,getRandom(6,8)+"");
    	}
    	String PlamRate = (String)redisUtils.hGet("PlamRate:"+ymd, ymd);
    	if(StringUtils.isBlank(PlamRate)){
    		redisUtils.hSet("PlamRate:"+ymd,ymd,getRandom(75,80)+"");
    	}
    	
    	//resp.setTodayCharge(MoneyUtil.bigDecimal2String(todayCharge.multiply(getRate()), 0));
    	//resp.setTodayTotalOrder(MoneyUtil.bigDecimal2String(todayTotalOrder.multiply(getRate()), 0));
    	
    	String todayAmount = (String)redisUtils.hGet("todayAmount:"+ymd,ymd);
    	String todayOrder = (String)redisUtils.hGet("todayOrder:"+ymd,ymd);
    	resp.setTodayCharge(todayAmount);
    	resp.setTodayTotalOrder(todayOrder);

    	
    	resp.setSevenDayAvgCharge(getSevenAvgCharge("todayAmount"));
    	resp.setSevenDayAvgOrder(getSevenAvgCharge("todayOrder"));
    	resp.setYestodayAvgUser(getSevenAvgCharge("todayUserCount"));
    	
    	
    	resp.setYestodayUserCount(str1);
    	resp.setYestodayNewUser(str2);
    	resp.setYestodayAvgUserPlam(str3);
    	resp.setYestodayUserRate(str4);
    	resp.setYestodayPlamRate(str5);
    	//当前设备在线比例
    	BigDecimal onlineRate = getRandomRate(75,78);
    	String onlineRateR = (String)redisUtils.hGet("onlineRate:"+ymd, ymd);
    	if(StringUtils.isBlank(onlineRateR)){
    		redisUtils.hSet("onlineRate:"+ymd,ymd,MoneyUtil.bigDecimal2String(onlineRate, 2));
    	}
    	String onlineRateFD = (String)redisUtils.hGet("onlineRateFD:"+ymd, ymd);
    	if(!StringUtils.isBlank(onlineRateFD)){
    		onlineRate = new BigDecimal(onlineRateFD);
    	}
    	//落地设备
    	//在线设备
    	BigDecimal ldPlam = new BigDecimal(totalCount).multiply(onlineRate);
    	String OnlinePlam = MoneyUtil.bigDecimal2String(ldPlam, 0);
    	String NowOnlineRate = MoneyUtil.bigDecimal2String(onlineRate.multiply(new BigDecimal(100)), 1);
     	
    	
    	String NowOnlineRateR = (String)redisUtils.hGet("NowOnlineRate:"+ymd, ymd);
    	if(StringUtils.isBlank(NowOnlineRateR)){
    		redisUtils.hSet("NowOnlineRate:"+ymd,ymd,NowOnlineRate);
    	}
    	String PlamRateR = (String)redisUtils.hGet("OnlinePlam:"+ymd, ymd);
    	if(StringUtils.isBlank(PlamRateR)){
    		redisUtils.hSet("OnlinePlam:"+ymd,ymd,OnlinePlam);
    	}
    	
    	resp.setNowOnlineRate(NowOnlineRateR);
    	resp.setOnlinePlam(PlamRateR);
    	resp.setTotalPlam(totalCount+"");
    	
    	return new Result<TodayDataResp>().ok(resp);
    }
    //7天平均充值
    public String getSevenAvgCharge(String code){
    	int count = 0;
    	BigDecimal total = BigDecimal.ZERO;
		for(int i = 1;i<=7;i++){
			String date = ZqDateUtil.yyyyMMdd(ZqDateUtil.addDate(ZqDateUtil.getNow(), -i, Calendar.DAY_OF_MONTH));
			String amount = (String)redisUtils.hGet(code+":"+date, date);
			if(!StringUtils.isBlank(amount)){
				total = total.add(MoneyUtil.convertBigDecimal(amount));
				count ++;
			}
		}
		if(count == 0){
			return "0";
		}
		BigDecimal va = total.divide(new BigDecimal(count), 2, BigDecimal.ROUND_HALF_UP);
		return MoneyUtil.bigDecimal2String(va, 0);
    }
    //获取当前小时
    public int getHour(){
		Calendar calendar = Calendar.getInstance();
		int curHour24 = calendar.get(calendar.HOUR_OF_DAY);
		return curHour24;
    }
    //获取范围内随机数
    public int getRandom(int start,int end){
        int a = ThreadLocalRandom.current().nextInt(start, end);
        return a;
    }
    //获取范围内随机数(百分比)
    public BigDecimal getRandomRate(int start,int end){
        int a = ThreadLocalRandom.current().nextInt(start, end);
        BigDecimal rate = new BigDecimal(a).divide(new BigDecimal(100));
        return rate;
    }

    //获取时间段比例
    public BigDecimal getRate(){
    	//0:00~11:00占5%  11:00~14:00占20%  14:00~17:00占10%  
    	//17:00~20:00占35%  20:00~24:00占30%
    	int hour = getHour();
    	if(hour >= 0 && hour <= 11){
    		return new BigDecimal(0.05);
    	}else if(hour > 11 && hour <= 14){
    		return new BigDecimal(0.2);
    	}else if(hour > 14 && hour <= 17){
    		return new BigDecimal(0.1);
    	}else if(hour > 17 && hour <= 20){
    		return new BigDecimal(0.35);
    	}else if(hour > 20 && hour <= 24){
    		return new BigDecimal(0.3);
    	}
    	return BigDecimal.ZERO;
    }
    
    
    /**
     * 订单列表
     * @param dto
     * @param request
     * @return
     */
    @PostMapping("orderList")
    @ApiOperation("订单列表")
    public Result<OrderListResp> orderList(HttpServletRequest request){
    	
        OrderListResp resp = new OrderListResp();
        
        List<SevenOrderDataResp> sevenOrder = new ArrayList<SevenOrderDataResp>();
        for(int i = 0;i<=6;i++){
        	SevenOrderDataResp resp1 = new SevenOrderDataResp();
			String date = ZqDateUtil.yyyyMMdd(ZqDateUtil.addDate(ZqDateUtil.getNow(), -i, Calendar.DAY_OF_MONTH));
			String date1 = ZqDateUtil.MM_dd(ZqDateUtil.addDate(ZqDateUtil.getNow(), -i, Calendar.DAY_OF_MONTH));
			String amount = (String)redisUtils.hGet("todayAmount:"+date, date);
			if(StringUtils.isBlank(amount)){
				amount = "0";
			}
			resp1.setAmount(amount);
			resp1.setDate(date1.replace("-", "/"));
			sevenOrder.add(resp1);
		}
        
        String cityData = "张家港-8%,银川-7.6%,合肥-7.5%,晋江-7.2%,焦作-6.4%,深圳-6%,蚌埠-5.2%,瑞安-4.3%,杭州-4%,南宁-3.9%";
        List<OrderCityDataResp> orderCity = new ArrayList<OrderCityDataResp>();
        for(int i = 0;i<cityData.split(",").length;i++){
        	OrderCityDataResp resp2 = new OrderCityDataResp();
        	String mes = cityData.split(",")[i];
        	String city = mes.split("-")[0];
        	String data = mes.split("-")[1];
        	
        	resp2.setCity(city);
        	resp2.setOrderNum(data);
        	orderCity.add(resp2);
        }
        
        String strOrder = (String)redisUtils.hGet("allOderList:", "order");
        
        List<OrderDataListResp> orderList = new ArrayList<OrderDataListResp>();
        String saveMes = "";
        int a = 1;
        for(int i = 0;i<4;i++){
        	String ord = strOrder.split("#")[i];
        	if(!StringUtils.isBlank(ord)){
        		if(StringUtils.isBlank(saveMes)){
        			saveMes = ord;
        		}else{
        			saveMes = saveMes+"#"+ord;        			
        		}
            	OrderDataListResp resp3 = new OrderDataListResp();
            	resp3.setId(a+"");
            	resp3.setOrderNo(ord.split(",")[0]);
            	resp3.setAmount(ord.split(",")[1]);
            	resp3.setImei(ord.split(",")[2]);
            	resp3.setChargeStatus("是");
            	resp3.setPayStatus("是");
            	resp3.setCreateTime(ord.split(",")[3]);
            	orderList.add(resp3);
            	a++;
        	}
        }
        
        //redisUtils
        
        
        resp.setOrderCity(orderCity);
        resp.setOrderList(orderList);
        resp.setSevenOrder(sevenOrder);
        return new Result<OrderListResp>().ok(resp);
    }
    
    /**
     * 修改数据
     * @param dto
     * @param request
     * @return
     */
    @PostMapping("updateData")
    @ApiOperation("修改数据")
    public Result<Object> updateData(@RequestBody UpdateDataReq dto,HttpServletRequest request){
    	TodayDataResp resp = new TodayDataResp();
		redisUtils.hSet(dto.getFild(),dto.getKey(),dto.getValue());
    	return new Result<Object>();
    }

}